package view;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;

import javax.swing.DefaultListModel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.ListModel;
import javax.swing.border.EmptyBorder;

import control.GeneralControll;

import objects.ConfiguracoesCliente;
import view.ConfigView.Tela;



public class ConfigView extends JFrame implements ActionListener{
public enum Tela{
	CLIENTE,CHEFE
}
	private JPanel contentPane;
	private ClientesView clientesView;
	private JTextField textFieldSetor;
	private JTextField textFieldIPServidor;
	private Tela tela;
	private JLabel lblAtendentes;
	private JList<String> listAtendente ;
	private JButton btnAplicar;
	private JButton btnCancelar;
	private JButton btnAdicionar;
	private JButton btnLimpar;
	private JCheckBox chckbxCliente ;
	private JLabel lblNewLabelsetor;
	private JLabel lblIpservidor;
	private JLabel lblCaminhoDados;
	private JTextField textFieldCaminho;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ConfigView frame = new ConfigView();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public ConfigView() {
		setTitle("Configura\u00E7\u00F5es");
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		
		 lblNewLabelsetor = new JLabel("Setor: ");
		
		textFieldSetor = new JTextField();
		textFieldSetor.setColumns(10);
		
		 lblIpservidor = new JLabel("ipServidor:");
		
		textFieldIPServidor = new JTextField();
		textFieldIPServidor.setToolTipText("<IP_SERVIDOR>:<PORT>");
		textFieldIPServidor.setColumns(10);
		
		 lblAtendentes = new JLabel("Atendentes:");
		
		 listAtendente = new JList();
		
		 btnAplicar = new JButton("Aplicar");
		
		 btnCancelar = new JButton("Cancelar");
		
		 btnAdicionar = new JButton("Adicionar");
		
		 btnLimpar = new JButton("Limpar");
		
		 chckbxCliente = new JCheckBox("Cliente");
		 chckbxCliente.setSelected(true);
		 
		 
		 
		 chckbxCliente.addActionListener(this);
		 btnCancelar.addActionListener(this);
		 btnAplicar.addActionListener(this);
		 btnAdicionar.addActionListener(this);
		 btnLimpar.addActionListener(this);
		 
		 
		 lblCaminhoDados = new JLabel("Caminho Dados:");
		
		textFieldCaminho = new JTextField();
		textFieldCaminho.setColumns(10);
		GroupLayout gl_contentPane = new GroupLayout(contentPane);
		gl_contentPane.setHorizontalGroup(
			gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPane.createSequentialGroup()
					.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
						.addComponent(lblNewLabelsetor)
						.addComponent(lblIpservidor)
						.addComponent(lblAtendentes)
						.addComponent(lblCaminhoDados))
					.addGap(26)
					.addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING)
						.addGroup(gl_contentPane.createSequentialGroup()
							.addComponent(btnAplicar)
							.addPreferredGap(ComponentPlacement.UNRELATED)
							.addComponent(btnCancelar)
							.addContainerGap())
						.addGroup(gl_contentPane.createSequentialGroup()
							.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING, false)
								.addComponent(listAtendente, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
								.addComponent(textFieldSetor)
								.addComponent(textFieldIPServidor, GroupLayout.DEFAULT_SIZE, 118, Short.MAX_VALUE)
								.addComponent(textFieldCaminho))
							.addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING)
								.addGroup(gl_contentPane.createSequentialGroup()
									.addPreferredGap(ComponentPlacement.RELATED)
									.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING, false)
										.addComponent(btnLimpar, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
										.addComponent(btnAdicionar, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
									.addContainerGap(119, Short.MAX_VALUE))
								.addGroup(gl_contentPane.createSequentialGroup()
									.addPreferredGap(ComponentPlacement.RELATED)
									.addComponent(chckbxCliente))))))
		);
		gl_contentPane.setVerticalGroup(
			gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPane.createSequentialGroup()
					.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_contentPane.createSequentialGroup()
							.addContainerGap()
							.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
								.addComponent(lblNewLabelsetor)
								.addComponent(textFieldSetor, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
							.addGap(18)
							.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
								.addComponent(lblIpservidor)
								.addComponent(textFieldIPServidor, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
						.addComponent(chckbxCliente))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_contentPane.createSequentialGroup()
							.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
								.addComponent(lblAtendentes)
								.addComponent(btnAdicionar))
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(btnLimpar)
							.addGap(59)
							.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
								.addComponent(lblCaminhoDados)
								.addComponent(textFieldCaminho, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
							.addPreferredGap(ComponentPlacement.RELATED, 23, Short.MAX_VALUE)
							.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
								.addComponent(btnAplicar)
								.addComponent(btnCancelar)))
						.addComponent(listAtendente, GroupLayout.PREFERRED_SIZE, 101, GroupLayout.PREFERRED_SIZE)))
		);
		contentPane.setLayout(gl_contentPane);
		setVisibilidade(false);
		listAtendente.setModel(setListAntedente());
		
		ConfiguracoesCliente cc;
		try {
			cc = GeneralControll.carregaConfig();
			textFieldSetor.setText(cc.getSetor());
			textFieldIPServidor.setText(cc.getIpServidor());
			textFieldCaminho.setText(cc.getPath().toString());
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			JOptionPane.showMessageDialog(this, "Erro desconhecido");
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	

	private DefaultListModel<String> setListAntedente() {
		// TODO Auto-generated method stub
		DefaultListModel<String> dm = new DefaultListModel<String>();
		try {
			ConfiguracoesCliente cc = GeneralControll.carregaConfig();
			ArrayList<String> atentendes = cc.getAtendetes();
			for(String nome : atentendes){
				dm.addElement(nome);				
			}
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			JOptionPane.showMessageDialog(this, "Arquivo de Configura��o n�o encontrado. Criado um novo");
			e.printStackTrace();
		}
		return dm;
	}

	public ConfigView(Tela t){
		this();
		chckbxCliente.setVisible(false);
	}

	public ConfigView(Tela cliente, ClientesView clientesView) {
		// TODO Auto-generated constructor stub
		this(cliente);
		this.clientesView = clientesView;
	}

	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		if(e.getSource() == btnAplicar){
			
			
			
			String setor = textFieldSetor.getText();
			String ipConfig = textFieldIPServidor.getText();
			boolean isClient = chckbxCliente.isSelected();
			Path path = Paths.get(textFieldCaminho.getText());
			System.out.println(path.toString());
			
			ArrayList<String> atendentes = geraAtendentes();			
			try {
				try {
					GeneralControll.gravarNovo(setor,ipConfig,isClient,path,atendentes);
				} catch (ClassNotFoundException e1) {
					// TODO Auto-generated catch block
					JOptionPane.showMessageDialog(this, "Erro interno grave");
					e1.printStackTrace();
				}
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
				JOptionPane.showMessageDialog(this, "Impossibilidade de gravar o arquivo de configura��o");
			}			
			
			
			
		//	JOptionPane.showMessageDialog(this, "Configura��o salva");
			
//gambis
			
			if(clientesView!=null){
				clientesView.carregaText();
			}
			
			
			this.dispose();
			
			
			

			
			
		}else if(e.getSource() == btnCancelar){
			
			this.dispose();
		}else if(e.getSource() == chckbxCliente){
			JCheckBox check = (JCheckBox)e.getSource();
			if(check.isSelected()){				
				setVisibilidade(false);			    
			}else{
				setVisibilidade(true);
			}			
		}else if(e.getSource()== btnAdicionar ){
			new AddAtendenteView(listAtendente).setVisible(true);
		}else if(e.getSource()==btnLimpar){
			DefaultListModel<String> listModel = new DefaultListModel<String>();
			listAtendente.setModel(listModel);
		}
	}

	private ArrayList<String> geraAtendentes() {
		// TODO Auto-generated method stub
		ArrayList<String> atendentes = new ArrayList<String>();
		DefaultListModel<String> qq = (DefaultListModel<String>) listAtendente.getModel();
		
		for(int i =0;i<qq.getSize();i++){
			atendentes.add(qq.get(i));
		}
		return atendentes;
	}

	private void setVisibilidade(boolean b) {
		// TODO Auto-generated method stub
		lblAtendentes.setVisible(b);
		listAtendente.setVisible(b);
		btnAdicionar.setVisible(b);
		btnLimpar.setVisible(b);
		lblCaminhoDados.setVisible(b);
		textFieldCaminho.setVisible(b);
	}
}
